<template>
  <div>
    <h1>登录</h1>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <button type="submit">登录</button>
    </form>
    <p v-if="error" class="error">{{ error }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

const username = ref('')
const password = ref('')
const error = ref('')

const handleLogin = async () => {
  try {
    await store.dispatch('login', { username: username.value, password: password.value })
    console.log('验证成功了', username.value, password.value, router)

    router.replace('/students') // 成功登录后跳转到学生列表页面
  } catch (error) {
    error.value = '登录失败，请检查用户名和密码。'
  }
}
</script>

<style>
.error {
  color: red;
}
</style>
